package com.geek.water.security;

import cn.hutool.core.collection.CollUtil;
import com.geek.water.entity.Permission;
import com.geek.water.entity.Role;
import com.geek.water.entity.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 如果已计算过权限，直接返回缓存结果
        if (CollUtil.isNotEmpty(authorities)) {
            return authorities;
        }

        authorities = new ArrayList<>();
        List<Role> roles = user.getRoles();

        // 确保roles不为空
        if (CollUtil.isNotEmpty(roles)) {
            for (Role role : roles) {
                // 生成Spring Security标准角色标识 (添加ROLE_前缀)
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));

                // 添加关联权限
                List<Permission> permissions = role.getPermissions();
                if (CollUtil.isNotEmpty(permissions)) {
                    for (Permission permission : permissions) {
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return "enabled".equals(user.getStatus());
    }
}